import Vue from 'vue'
import VueRouter from 'vue-router'
import Admin from '_views/Admin'
import store from '../store'
import { isLogin } from '_utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'admin',
    component: Admin,
    children: [
      {
        path: '/',
        redirect: '/dashBoard'
      },
      {
        path: '/dashBoard',
        name: '仪表盘',
        meta: {
          roles: ['a', 'b', 'c', 'admin']
        },
        component: () => import('_views/DashBoard')
      },
      {
        path: '/itemLists',
        name: '商品列表',
        meta: {
          roles: ['a', 'b', 'c', 'admin']
        },
        component: () => import('_views/ItemLists')
      },
      {
        path: '/itemAdd',
        name: '增加商品',
        meta: {
          roles: ['a', 'b', 'c', 'admin']
        },
        component: () => import('_views/ItemAdd')
      },
      {
        path: '/itemUpdate',
        name: '更新商品',
        meta: {
          roles: ['a', 'b', 'c', 'admin']
        },
        component: () => import('_views/ItemUpdate')
      },
      {
        path: '/cateLists',
        name: '商品分类管理',
        meta: {
          roles: ['a', 'b', 'c', 'admin']
        },
        component: () => import('_views/CateLists')
      },
      {
        path: '/user',
        name: '个人中心',
        meta: {
          roles: '*'
        },
        component: () => import('_views/User')
      },
      {
        path: '/settings',
        name: '设置',
        meta: {
          roles: ['a', 'b', 'c']
        },
        component: () => import('_views/Settings')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      roles: '*'
    },
    component: () => import('_views/Login')
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      roles: '*'
    },
    component: () => import('_views/Login')
  },
  {
    path: '/noAuth',
    name: 'noAuth',
    meta: {
      roles: '*'
    },
    component: () => import('_views/NoAuth')
  },
  {
    path: '*',
    name: 'notFound',
    meta: {
      roles: '*'
    },
    component: () => import('_views/NotFound')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 登录鉴权
router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    // 判断是否登录
    if (isLogin()) {
      // 判断当前用户角色是否可以访问该路由
      const role = localStorage.getItem('role')
      if (to.meta.roles === '*' || to.meta.roles.includes(role)) {
        // 当前角色可以访问的
        next()
      } else {
        // 跳转到没有权限这个页面
        next('/noAuth')
      }
    } else {
      // 没有登录
      // 去登录去
      next('/login')
    }
  } else {
    next()
  }
})
// 路由后置守卫 实现路由变化，自动添加头部 navTab
router.afterEach((to) => {
  // 待添加的 tab导航
  const tab = {
    name: to.name,
    path: to.path
  }
  store.commit('base/ADD_NAV_TAB', tab)
})

export default router
